#pragma once
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
#include <sys/select.h>
#include "log.hpp"
#include "Err.hpp"
#include "Sock.hpp"

static const uint16_t default_port = 8888;
using type_t = int;

class SelectServer
{
    static const int N = sizeof(fd_set) * 8;

public:
    SelectServer(uint16_t port = default_port) : _port(port)
    {
    }

    void InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        // 初始化接收fd的数组
        for (int i = 0; i < N; i++)
            fdarray[i] = default_fd;
    }

    void Start()
    {
        // 将监听socket插入
        LogMessage(Info, "ready to provide service");
        fdarray[0] = _listensock.GetFd();
        while (true)
        {
            // 初始化需要被监听的所有fd到结构体中
            fd_set rfds;
            FD_ZERO(&rfds);
            int max_fd = fdarray[0];
            for (int i = 0; i < N; i++)
            {
                if (fdarray[i] == -1)
                    continue;
                FD_SET(fdarray[i], &rfds);
                // 找到最大的fd
                if (max_fd < fdarray[i])
                    max_fd = fdarray[i];
            }

            int n = select(max_fd + 1, &rfds, nullptr, nullptr, nullptr);
            switch (n)
            {
            case 0:
                LogMessage(Info, "time out, %d: %s", errno, strerror(errno));
                break;
            case -1:
                LogMessage(Warring, "%d: %s", errno, strerror(errno));
                break;
            default:
                LogMessage(Info, "There are %d things ready", n);
                EventHandler(rfds);
                break;
            }
        }
    }

    void EventHandler(fd_set rfds)
    {
        for (int i = 0; i < N; i++)
        {
            if (fdarray[i] == -1)
                continue;
            if (fdarray[i] == _listensock.GetFd() && FD_ISSET(fdarray[i], &rfds))
            {
                Accept();
            }

            if (fdarray[i] != _listensock.GetFd() && FD_ISSET(fdarray[i], &rfds))
            {
                Read(i);
            }
        }
    }

    void Accept()
    {
        std::string client_ip;
        uint16_t client_port;
        int sock = _listensock.Accept(&client_ip, &client_port);

        int pos = 1;
        for (; pos < N; pos++)
        {
            if (fdarray[pos] == default_fd)
                break;
        }

        if (pos >= N)
        {
            close(sock);
            LogMessage(Bug, "fdarray is full");
        }
        else
        {
            LogMessage(Info, "new sock fdarray[] -> %d", sock);
            fdarray[pos] = sock;
        }
    }

    void Read(int index)
    {
        char buffer[1024];
        int n = read(fdarray[index], buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = 0;
            std::cout << "client# " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LogMessage(Info, "client quit..., sock: %d", fdarray[index]);
            fdarray[index] = default_fd;
            close(fdarray[index]);
        }
        else
        {
        }
    }

    ~SelectServer()
    {
    }

private:
    uint16_t _port;
    Sock _listensock;
    type_t fdarray[N];
};
